﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using VSM.Utils;
namespace SAP
{
    public partial class Popup_Vehice : System.Web.UI.Page
    {
        
        
        private static string VIN = "";
        private static string dbType;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                dbType = Session[VSM.Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? VSM.Utils.AppConstants.VSM : VSM.Utils.AppConstants.DEALER;
                VIN = Request.QueryString["VIN"] == null ? "" : Request.QueryString["VIN"];
                int RequestType = Request.QueryString["requestType"] == null ? 0 : Int32.Parse(Request.QueryString["requestType"]);

                disaenaControl(false);
                txt_RegNo.Enabled = true;
                editItemUpdatePanel.Update();
                //VehicleID
            }
        }
        private string FormatDate(string dateIn)
        {
            if (dateIn.Trim() == "")
                return "";
            DateTime pars = DateTime.Parse(dateIn);
            return pars.ToString("dd/MM/yyyy");

        }

        private void disaenaControl(bool fot) {
            txt_Brand.Enabled = fot;
            txt_VehicleName.Enabled = fot;
            txt_EngineNo.Enabled = fot;
            txt_RegNo.Enabled = fot;
            txt_KeyNo.Enabled = fot;
            txt_ProdDate.Enabled = fot;
            txt_PDIDate.Enabled = fot;

            txt_InvoiceDate.Enabled = fot;
            txt_Dealer.Enabled = fot;
            txt_ColorCode.Enabled = fot;
            txt_CustomerCode.Enabled = fot;
            txt_CustomerName.Enabled = fot;
            txt_LotNo.Enabled = fot;
            txt_Remarks.Enabled = fot;
            txt_Model.Enabled = fot;
        }

        private void loadVehicleByVIN() {
            if (VIN == "")
                return;
            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery(dbType, "select * from U_ServiceVehicle where VIN = '" + VIN + "'");
            if (ds.Tables[0].Rows.Count > 0)
            {
                Session["VehicleID"] = ds.Tables[0].Rows[0]["VehicleID"];
                hf_VehicleID.Value = Session["VehicleID"].ToString();
                txt_VIN.Text = ds.Tables[0].Rows[0]["VIN"].ToString();
                txt_Brand.Text = ds.Tables[0].Rows[0]["Brand"].ToString(); 
                txt_VehicleName.Text = ds.Tables[0].Rows[0]["VehicleName"].ToString();
                txt_EngineNo.Text = ds.Tables[0].Rows[0]["EngineNo"].ToString();
                txt_RegNo.Text = ds.Tables[0].Rows[0]["RegNo"].ToString();

                txt_KeyNo.Text = ds.Tables[0].Rows[0]["KeyNo"].ToString();
                txt_ProdDate.Text = FormatDate(ds.Tables[0].Rows[0]["ProductionDate"].ToString());
                txt_PDIDate.Text = FormatDate(ds.Tables[0].Rows[0]["PDIDate"].ToString());

                txt_InvoiceDate.Text = FormatDate(ds.Tables[0].Rows[0]["InvoiceDate"].ToString());
                txt_Dealer.Text = ds.Tables[0].Rows[0]["Dealer"].ToString();
                txt_ColorCode.Text = ds.Tables[0].Rows[0]["ColorCode"].ToString();
                txt_CustomerCode.Text = ds.Tables[0].Rows[0]["CustomerCode"].ToString();
                txt_CustomerName.Text = ds.Tables[0].Rows[0]["CustomerName"].ToString();
                txt_LotNo.Text = ds.Tables[0].Rows[0]["LotNo"].ToString();

                txt_Remarks.Text = ds.Tables[0].Rows[0]["Remarks"].ToString();
                txt_Model.Text = ds.Tables[0].Rows[0]["Model"].ToString();
                loadCustomerFromService(VIN);
            }
            else
            {
                ResetField();
                lb_Message.Text = "No Data Found.";
            }
        }

        private void loadVehicleByRegNum(string regNum)
        {
            if (regNum == "")
                return;
            Services sv = new Services();
            string sql = "select * from U_ServiceVehicle where RegNo = '" + regNum + "'";
            DataSet ds = sv.ExecuteQuery("DEALER", sql);
            if (ds.Tables[0].Rows.Count > 0)
            {
                Session["VehicleID"] = (int)ds.Tables[0].Rows[0]["VehicleID"];
                hf_VehicleID.Value = Session["VehicleID"].ToString();
                txt_VIN.Text = ds.Tables[0].Rows[0]["VIN"].ToString();
                txt_Brand.Text = ds.Tables[0].Rows[0]["Brand"].ToString();
                txt_VehicleName.Text = ds.Tables[0].Rows[0]["VehicleName"].ToString();
                txt_EngineNo.Text = ds.Tables[0].Rows[0]["EngineNo"].ToString();
                txt_RegNo.Text = ds.Tables[0].Rows[0]["RegNo"].ToString();

                txt_KeyNo.Text = ds.Tables[0].Rows[0]["KeyNo"].ToString();
                txt_ProdDate.Text = FormatDate(ds.Tables[0].Rows[0]["ProductionDate"].ToString());
                txt_PDIDate.Text = FormatDate(ds.Tables[0].Rows[0]["PDIDate"].ToString());

                txt_InvoiceDate.Text = FormatDate(ds.Tables[0].Rows[0]["InvoiceDate"].ToString());
                txt_Dealer.Text = ds.Tables[0].Rows[0]["Dealer"].ToString();
                txt_ColorCode.Text = ds.Tables[0].Rows[0]["ColorCode"].ToString();
                txt_CustomerCode.Text = ds.Tables[0].Rows[0]["CustomerCode"].ToString();
                txt_CustomerName.Text = ds.Tables[0].Rows[0]["CustomerName"].ToString();
                txt_LotNo.Text = ds.Tables[0].Rows[0]["LotNo"].ToString();

                txt_Remarks.Text = ds.Tables[0].Rows[0]["Remarks"].ToString();
                txt_Model.Text = ds.Tables[0].Rows[0]["Model"].ToString();

                string sqlCus = "select CustomerCode, CustomerName, OtherName, Address, Tel, Mobile, TaxCode, ContactPerson, ContactPhone  from U_GeneralService where RegNo = '" + regNum + "'";
                DataSet dsCus = sv.ExecuteQuery("DEALER", sqlCus);
                if (dsCus.Tables[0].Rows.Count > 0) {
                    hf_CustomerCode.Value = dsCus.Tables[0].Rows[0]["CustomerCode"].ToString();
                    hf_CustomerName.Value = dsCus.Tables[0].Rows[0]["CustomerName"].ToString();
                    hf_OtherName.Value = dsCus.Tables[0].Rows[0]["OtherName"].ToString();
                    hf_Address.Value = dsCus.Tables[0].Rows[0]["Address"].ToString();
                    hf_Tel.Value = dsCus.Tables[0].Rows[0]["Tel"].ToString();
                    hf_TaxCode.Value = dsCus.Tables[0].Rows[0]["TaxCode"].ToString();
                    hf_ContactPerson.Value = dsCus.Tables[0].Rows[0]["ContactPerson"].ToString();
                    hf_PhoneContact.Value = dsCus.Tables[0].Rows[0]["ContactPhone"].ToString();
                }
            }
            else
            {
                ResetField();
                lb_Message.Text = "No Data Found.";
            }
        }

        private void loadVehicleByRegNumFromSalesData(string regNum) {
            if (regNum == "")
                return;
            Services sv = new Services();

            string sql = "select inv.DocDate as InvoiceDate, rn.DistNumber as VIN, rn.Notes as EngineNo, ms.Name as Model, ";
            sql += " cg.RegistrationNumber as RegNo, inv.CardCode as CustomerCode, inv.CardName as CustomerName, ";
            sql += " it.ItemName as VehicleName, rn.U_KeyNo as KeyNo, ms.Code as ModelCode, ";
            sql += " inv.U_DealerID as Dealer, it.U_Color as ColorCode, rn.LotNumber as LotNo, it.UserText as Remarks, '' as Brand, ";
            sql += " ''as ProductionDate, '' as PDIDate ";
            sql += " from OINV inv join INV1 inv1 on inv.DocEntry = inv1.BaseEntry ";
            sql += " join  OSRN rn on inv1.ItemCode = rn.ItemCode ";
            sql += " join OITM it on it.ItemCode = inv1.ItemCode ";
            sql += " join [@ModelSales] ms on ms.Code = it.U_ModelSales ";
            sql += " left join U_CustomerRegis cg on cg.VIN = rn.DistNumber ";
            sql += " where cg.RegistrationNumber = '" + regNum + "' ";
            DataSet ds = sv.ExecuteQuery("VSM", sql);

            if (ds.Tables[0].Rows.Count > 0)
            {
                Session["VehicleID"] = ds.Tables[0].Rows[0]["VIN"].ToString();// (int)ds.Tables[0].Rows[0]["VehicleID"];
                hf_VehicleID.Value = Session["VehicleID"].ToString();
                txt_VIN.Text = ds.Tables[0].Rows[0]["VIN"].ToString();
                txt_Brand.Text = ds.Tables[0].Rows[0]["Brand"].ToString();
                txt_VehicleName.Text = ds.Tables[0].Rows[0]["VehicleName"].ToString();

                string CompressNo = ds.Tables[0].Rows[0]["EngineNo"].ToString();
                if (CompressNo.Length > 4)
                {
                    txt_Model.Text =  CompressNo.Substring(0, 4);
                    txt_EngineNo.Text = CompressNo.Substring(4, CompressNo.Length-4);
                }
                else
                {
                    txt_Model.Text = ds.Tables[0].Rows[0]["Model"].ToString();
                    txt_EngineNo.Text = ds.Tables[0].Rows[0]["EngineNo"].ToString();
                }
                txt_RegNo.Text = ds.Tables[0].Rows[0]["RegNo"].ToString();

                txt_KeyNo.Text = ds.Tables[0].Rows[0]["KeyNo"].ToString();
                txt_ProdDate.Text =  FormatDate(ds.Tables[0].Rows[0]["ProductionDate"].ToString());
                txt_PDIDate.Text = FormatDate(ds.Tables[0].Rows[0]["PDIDate"].ToString());

                txt_InvoiceDate.Text = FormatDate(ds.Tables[0].Rows[0]["InvoiceDate"].ToString());
                txt_Dealer.Text = ds.Tables[0].Rows[0]["Dealer"].ToString();
                txt_ColorCode.Text = ds.Tables[0].Rows[0]["ColorCode"].ToString();
                txt_CustomerCode.Text = ds.Tables[0].Rows[0]["CustomerCode"].ToString();
                txt_CustomerName.Text = ds.Tables[0].Rows[0]["CustomerName"].ToString();
                txt_LotNo.Text = ds.Tables[0].Rows[0]["LotNo"].ToString();

                txt_Remarks.Text = ds.Tables[0].Rows[0]["Remarks"].ToString();
                loadCustomerByVehicle(ds.Tables[0].Rows[0]["CustomerCode"].ToString());
                btn_Save.Enabled = false;
                btn_Modify.Enabled = false;
            }
            else
            {
                ResetField();
                lb_Message.Text = "No Data Found.";
            }
        }

        private void loadVehicleByVINFromSaleData()
        {
            if (VIN == "")
                return;
            Services sv = new Services();
            
            string sql = "select inv.DocDate as InvoiceDate, rn.DistNumber as VIN, rn.Notes as EngineNo, ms.Name as Model, ";
            sql += " cg.RegistrationNumber as RegNo, inv.CardCode as CustomerCode, inv.CardName as CustomerName, ";
            sql += " it.ItemName as VehicleName, rn.U_KeyNo as KeyNo, ms.Code as ModelCode, ";
            sql += " inv.U_DealerID as Dealer, it.U_Color as ColorCode, rn.LotNumber as LotNo, it.UserText as Remarks, '' as Brand, ";
            sql += " ''as ProductionDate, '' as PDIDate ";
            sql += " from OINV inv join INV1 inv1 on inv.DocEntry = inv1.BaseEntry ";
            sql += " join  OSRN rn on inv1.ItemCode = rn.ItemCode ";
            sql += " join OITM it on it.ItemCode = inv1.ItemCode ";
            sql += " join [@ModelSales] ms on ms.Code = it.U_ModelSales ";
            sql += " left join U_CustomerRegis cg on cg.VIN = rn.DistNumber ";
            sql += " where rn.DistNumber = '" + VIN + "' ";
            DataSet ds = sv.ExecuteQuery("VSM", sql);

            if (ds.Tables[0].Rows.Count > 0)
            {
                Session["VehicleID"] = ds.Tables[0].Rows[0]["VIN"].ToString();// (int)ds.Tables[0].Rows[0]["VehicleID"];
                hf_VehicleID.Value = Session["VehicleID"].ToString();
                txt_VIN.Text = ds.Tables[0].Rows[0]["VIN"].ToString();
                txt_Brand.Text = ds.Tables[0].Rows[0]["Brand"].ToString();
                txt_VehicleName.Text = ds.Tables[0].Rows[0]["VehicleName"].ToString();
                string CompressNo = ds.Tables[0].Rows[0]["EngineNo"].ToString();
                if (CompressNo.Length > 4)
                {
                    txt_Model.Text = CompressNo.Substring(0, 4);
                    txt_EngineNo.Text = CompressNo.Substring(4, CompressNo.Length - 4);
                }
                else
                {
                    txt_Model.Text = ds.Tables[0].Rows[0]["Model"].ToString();
                    txt_EngineNo.Text = ds.Tables[0].Rows[0]["EngineNo"].ToString();
                }
                txt_RegNo.Text = ds.Tables[0].Rows[0]["RegNo"].ToString();

                txt_KeyNo.Text = ds.Tables[0].Rows[0]["KeyNo"].ToString();
                txt_ProdDate.Text = FormatDate(ds.Tables[0].Rows[0]["ProductionDate"].ToString());
                txt_PDIDate.Text = FormatDate(ds.Tables[0].Rows[0]["PDIDate"].ToString());

                txt_InvoiceDate.Text = FormatDate(ds.Tables[0].Rows[0]["InvoiceDate"].ToString());
                txt_Dealer.Text = ds.Tables[0].Rows[0]["Dealer"].ToString();
                txt_ColorCode.Text = ds.Tables[0].Rows[0]["ColorCode"].ToString();
                txt_CustomerCode.Text = ds.Tables[0].Rows[0]["CustomerCode"].ToString();
                txt_CustomerName.Text = ds.Tables[0].Rows[0]["CustomerName"].ToString();
                txt_LotNo.Text = ds.Tables[0].Rows[0]["LotNo"].ToString();

                txt_Remarks.Text = ds.Tables[0].Rows[0]["Remarks"].ToString();

                btn_Save.Enabled = false;
                btn_Modify.Enabled = false;

                loadCustomerByVehicle(ds.Tables[0].Rows[0]["CustomerCode"].ToString());
            }
            else
            {
                ResetField();
                lb_Message.Text = "No Data Found.";
            }
        }

        private void loadCustomerByVehicle(string CustomerCode) {
            string sql = "select CardCode, CardName, CardFName, [Address], Phone1, LicTradNum, U_ContactPerson, U_ContactPhone ";
            sql += "  from OCRD where CardCode = '"+ CustomerCode+ "'";
            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery("VSM", sql);
            if(ds.Tables[0].Rows.Count>0){
                hf_CustomerCode.Value = ds.Tables[0].Rows[0]["CardCode"].ToString();
                hf_CustomerName.Value = ds.Tables[0].Rows[0]["CardName"].ToString();
                hf_OtherName.Value = ds.Tables[0].Rows[0]["CardFName"].ToString();
                hf_Address.Value = ds.Tables[0].Rows[0]["Address"].ToString();
                hf_Tel.Value = ds.Tables[0].Rows[0]["Phone1"].ToString();
                hf_TaxCode.Value = ds.Tables[0].Rows[0]["LicTradNum"].ToString();
                hf_ContactPerson.Value = ds.Tables[0].Rows[0]["U_ContactPerson"].ToString();
                hf_PhoneContact.Value =ds.Tables[0].Rows[0]["U_ContactPhone"].ToString();
                
            }
        }

        private void loadCustomerFromService(string VIN) {
            string sql = "SELECT CustomerCode, CustomerName, OtherName, Address, Tel, Mobile, TaxCode, ContactPerson, ContactPhone from U_GeneralService WHERE VIN = '" + VIN + "'";
            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery("DEALER", sql);
            if (ds.Tables[0].Rows.Count > 0) {
                hf_CustomerCode.Value = ds.Tables[0].Rows[0]["CustomerCode"].ToString();
                hf_CustomerName.Value = ds.Tables[0].Rows[0]["CustomerName"].ToString();
                hf_OtherName.Value = ds.Tables[0].Rows[0]["OtherName"].ToString();
                hf_Address.Value = ds.Tables[0].Rows[0]["Address"].ToString();
                hf_Tel.Value = ds.Tables[0].Rows[0]["Tel"].ToString();
                hf_TaxCode.Value = ds.Tables[0].Rows[0]["TaxCode"].ToString();
                hf_ContactPerson.Value = ds.Tables[0].Rows[0]["ContactPerson"].ToString();
                hf_PhoneContact.Value = ds.Tables[0].Rows[0]["ContactPhone"].ToString();
            }
        }

        private void ResetField() {
            Session["VehicleID"] = -1;
            //txt_VIN.Text = "";
            txt_Brand.Text = "";
            txt_VehicleName.Text = "";
            txt_EngineNo.Text = "";
            //txt_RegNo.Text = "";

            txt_KeyNo.Text = "";
            txt_ProdDate.Text = "";
            txt_PDIDate.Text = "";
            
            txt_InvoiceDate.Text = "";
            txt_Dealer.Text = "";
            txt_ColorCode.Text = "";
            txt_CustomerCode.Text = "";
            txt_CustomerName.Text = "";
            txt_LotNo.Text = "";

            txt_Remarks.Text = "";
            txt_Model.Text = "";
        }

        protected void btn_New_Click(object sender, EventArgs e)
        {

            txt_VIN.Enabled = true;
            txt_Brand.Enabled = true;
            txt_VehicleName.Enabled = true;
            txt_EngineNo.Enabled = true;
            txt_RegNo.Enabled = true;
            txt_KeyNo.Enabled = true;
            txt_ProdDate.Enabled = false;
            txt_PDIDate.Enabled = false;

            txt_InvoiceDate.Enabled = false;
            txt_Dealer.Enabled = false;
            txt_ColorCode.Enabled = true;
            txt_CustomerCode.Enabled = false;
            txt_CustomerName.Enabled = false;
            txt_LotNo.Enabled = false;
            txt_Remarks.Enabled = true;
            txt_Model.Enabled = true;

            Image1.Visible = false;
            ImageButton4.Visible = false;
            ImageButton5.Visible = false;

            btn_Modify.Enabled = false;
            btn_Save.Enabled = true;
            ResetField();
        }

        protected void btn_Save_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("VIN");
            dt.Columns.Add("Brand");
            dt.Columns.Add("VehicleName");
            dt.Columns.Add("EngineNo");
            dt.Columns.Add("RegNo");
            dt.Columns.Add("KeyNo");
            dt.Columns.Add("ProductionDate");
            dt.Columns.Add("PDIDate");
            dt.Columns.Add("InvoiceDate");
            dt.Columns.Add("Dealer");
            dt.Columns.Add("ColorCode");
            dt.Columns.Add("CustomerCode");
            dt.Columns.Add("CustomerName");
            dt.Columns.Add("LotNo");
            dt.Columns.Add("Remarks");
            dt.Columns.Add("VehicleID");
            dt.Columns.Add("Model");

            DataRow dr = dt.NewRow();
            dr["VIN"] = txt_VIN.Text;
            dr["Brand"] = txt_Brand.Text;
            dr["VehicleName"] = txt_VehicleName.Text;
            dr["EngineNo"] = txt_EngineNo.Text;
            dr["RegNo"] = txt_RegNo.Text;
            dr["KeyNo"] = txt_KeyNo.Text;

            if (txt_ProdDate.Text.Trim() == "")
                dr["ProductionDate"] = DBNull.Value;
            else
                dr["ProductionDate"] = VSM.Utils.AppConstants.ConvertToDate(txt_ProdDate.Text.Trim());

            if (txt_PDIDate.Text.Trim() == "")
                dr["PDIDate"] = DBNull.Value;
            else
                dr["PDIDate"] = VSM.Utils.AppConstants.ConvertToDate(txt_PDIDate.Text.Trim());

            if (txt_InvoiceDate.Text.Trim() == "")
                dr["InvoiceDate"] = DBNull.Value;
            else
                dr["InvoiceDate"] = VSM.Utils.AppConstants.ConvertToDate(txt_InvoiceDate.Text.Trim());

            dr["Dealer"] = txt_Dealer.Text;
            dr["ColorCode"] = txt_ColorCode.Text;
            dr["CustomerCode"] = txt_CustomerCode.Text;
            dr["CustomerName"] = txt_CustomerName.Text;
            dr["LotNo"] = txt_LotNo.Text;
            dr["Remarks"] = txt_Remarks.Text;
            dr["VehicleID"] = Session["VehicleID"];
            dr["Model"] = txt_Model.Text;
            //save or add new
            if (Session["VehicleID"].ToString() == "-1")
            {
                Services svc = new Services();
                dt.Rows.Add(dr);
                DataSet ds = new DataSet();
                ds.Tables.Add(dt);
                Session["VehicleID"] = svc.InsertVehicle(dbType, ds);
                if (Session["VehicleID"].ToString() != "-1")
                {
                    hf_VehicleID.Value = Session["VehicleID"].ToString();
                    lb_Message.Text = "[Add New] Operation complete.";
                }
                else
                {
                    lb_Message.Text = "[Add New] Error occurs.";
                }
                
            }
            else {
                Services svc = new Services();
                dt.Rows.Add(dr);
                DataSet ds = new DataSet();
                ds.Tables.Add(dt);
                int result = svc.UpdateVehicle(dbType, ds);
                if (result == 1)
                {
                    lb_Message.Text = "[Update] Error occurs.";
                }
            }
        }
        //search by VIN
        // 1. Search in vehicle service table
        // 2. 
        protected void btn_Search_Click(object sender, EventArgs e)
        {
            if (txt_VIN.Text.Trim() == "")
            {
                lb_Message.Text = "Please input a VIN...";
            }
            else {
                VIN = txt_VIN.Text.Trim();
                loadVehicleByVIN();
                if(Session["VehicleID"].ToString() == "-1")
                    loadVehicleByVINFromSaleData();
            }
        }

        protected void btn_SearchRegNo_Click(object sender, EventArgs e)
        {
            if (txt_RegNo.Text.Trim() == "") {
                lb_Message.Text = "Please input a Registration Number...";
            }
            else
            {
                loadVehicleByRegNum(txt_RegNo.Text);
                if (txt_VIN.Text.Trim() == "")
                    loadVehicleByRegNumFromSalesData(txt_RegNo.Text);
            }

        }
    }
}